package com.fancon.rage.comic.vn.apiservice;

import java.io.IOException;
import java.net.URLDecoder;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.arnx.jsonic.JSONException;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;

import com.fancon.android.apiservice.ApiConnect;
import com.fancon.android.apiservice.FanconApiService;
import com.fancon.rage.comic.vn.entity.Photo;
import com.fancon.rage.comic.vn.gui.TopControlView;

public class RageApiService extends FanconApiService {
	public static final String ROOT_API = "http://ragecomicvn.appspot.com/";

	public RageApiService(Context context) {
		super(context, ROOT_API);
		// TODO Auto-generated constructor stub
	}

	public ArrayList<Photo> getAllComics(int mode) throws JSONException,
			IOException, org.json.JSONException, NoSuchAlgorithmException {
		List<NameValuePair> paramList = new ArrayList<NameValuePair>();
		paramList.add(new BasicNameValuePair("action", "all"));
		// String result = ApiConnect.execGet(ROOT_API+"ragejsonvn", paramList);
		ApiConnect api = new ApiConnect(mContext);
		String subUrl = null;
		if (mode == TopControlView.VN_MODE) {
			subUrl = "ragejsonvn";
		} else if (mode == TopControlView.EN_MODE) {
			subUrl = "ragecollectjson";
			paramList.add(new BasicNameValuePair("mode", "en"));
		}
		String result = api.getApiData(ROOT_API + subUrl, paramList);
		// Photo[] photos = (Photo[])decode(is, Photo[].class);
		ArrayList<Photo> photos = new ArrayList<Photo>();
		JSONArray jobjects = new JSONArray(result);
		JSONObject phoJson = null;
		for (int i = 0; i < jobjects.length(); i++) {
			phoJson = jobjects.getJSONObject(i);
			Photo photo = new Photo();
			if (phoJson.opt("id") != null) {
				photo.setId(phoJson.getLong("id"));
			}
			if (phoJson.opt("title") != null) {
				photo.setTitle(URLDecoder.decode(phoJson.getString("title"),
						"UTF-8"));
			}
			if (phoJson.opt("thumbUrl") != null) {
				photo.setThumbUrl(phoJson.getString("thumbUrl"));
			}
			if (phoJson.opt("imageUrl") != null) {
				photo.setImageUrl(phoJson.getString("imageUrl"));
			}
			if (phoJson.opt("date") != null) {
				photo.setDate(new Date(phoJson.getLong("date")));
			}
			photos.add(photo);
		}
		return photos;
	}
}